{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# KNN应用——手写识别系统\n",
    "\n",
    "1. 收集数据：32×32的黑白图像\n",
    "2. 准备数据：编写classify0()，将图像格式转换为分类器使用的list格式\n",
    "3. 分析数据：在Python命令提示符中检查数据，确保它符合要求\n",
    "4. 训练算法：此步骤不适用于k-近邻算法\n",
    "5. 测试算法\n",
    "6. 使用算法：本例未完成。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 准备数据：将图像转换为测试"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "from numpy import *\n",
    "def img2vector(filename):\n",
    "    returnVect = zeros((1,1024))\n",
    "    with open(filename) as f:\n",
    "        for i in range(32):\n",
    "            lineStr = f.readline()\n",
    "            for j in range(32):\n",
    "                returnVect[0, 32*i+j] = int(lineStr[j])\n",
    "    return returnVect"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[0., 0., 0., ..., 0., 0., 0.]])"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "img2vector('digits/testDigits/0_13.txt')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 测试算法：使用k-近邻算法识别手写数字"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "def classify0(intX, dataSet, labels ,k):\n",
    "    dataSetSize = dataSet.shape[0]\n",
    "    #1.计算距离\n",
    "    diffMat = tile(intX, (dataSetSize,1)) - dataSet\n",
    "    sqDiffMat = diffMat**2\n",
    "    sqDistance = sqDiffMat.sum(axis=1)\n",
    "    distances = sqDistance**0.5\n",
    "    #2.选择距离最小的k个点\n",
    "    sortedDistIndicies = distances.argsort()\n",
    "    classCount={}\n",
    "    for i in range(k):\n",
    "        voteIlabel = labels[sortedDistIndicies[i]]\n",
    "        classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1\n",
    "    #3.排序\n",
    "    sortedClassCount = sorted(classCount.items(), key=lambda item:item[1], reverse=True)\n",
    "    return sortedClassCount[0][0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [],
   "source": [
    "from os import listdir\n",
    "def handwritingClassTest():\n",
    "    #1.获取目录内容\n",
    "    hwLabels = []\n",
    "    traingFileList = listdir('digits/trainingDigits')\n",
    "    m = len(traingFileList) \n",
    "    #2.从文件名解析分类数字\n",
    "    trainingMat = zeros((m,1024))\n",
    "    for i in range(m):\n",
    "        fileNameStr = traingFileList[i]\n",
    "        fileStr = fileNameStr.split('.')[0]\n",
    "        classNumStr = int(fileStr.split('_')[0])\n",
    "        hwLabels.append(classNumStr)\n",
    "        trainingMat[i,:] = img2vector('digits/trainingDigits/%s' % fileNameStr)\n",
    "    #3.测试\n",
    "    testFileList = listdir('digits/testDigits')\n",
    "    errorCount = 0.0\n",
    "    mTest = len(testFileList)\n",
    "    for i in range(mTest):\n",
    "        fileNameStr = testFileList[i]\n",
    "        fileStr = fileNameStr.split('.')[0]\n",
    "        classNumStr = int(fileStr.split('_')[0])\n",
    "        vectorUnderTest = img2vector('digits/testDigits/%s' % fileNameStr)\n",
    "        classifierResult = classify0(vectorUnderTest, trainingMat, hwLabels, 3)\n",
    "#         print(\"分类器结果：%d,实际结果：%d\" % (classifierResult, classNumStr))\n",
    "        if classifierResult != classNumStr:errorCount += 1.0\n",
    "    print(\"总共分错个数：%d\" % errorCount)\n",
    "    print(\"总错分率：%f\" % (errorCount / float(mTest)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "总共分错个数：10\n",
      "总错分率：0.010571\n"
     ]
    }
   ],
   "source": [
    "handwritingClassTest()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
